<template>
  <div class="dashboard">
    <!-- 概览统计 -->
    <div class="stats-grid">
      <div class="status-card">
        <div class="title">总任务数</div>
        <div class="value">{{ statistics.totalTasks || 0 }}</div>
        <div class="subtitle">
          <el-icon><TrendCharts /></el-icon>
          活跃任务: {{ statistics.activeTasks || 0 }}
        </div>
      </div>

      <div class="status-card">
        <div class="title">今日执行</div>
        <div class="value">{{ statistics.todayExecutions || 0 }}</div>
        <div class="subtitle">
          <el-icon><SuccessFilled /></el-icon>
          成功率: {{ statistics.successRate || 0 }}%
        </div>
      </div>

      <div class="status-card">
        <div class="title">代码库数量</div>
        <div class="value">{{ statistics.totalRepositories || 0 }}</div>
        <div class="subtitle">
          <el-icon><FolderOpened /></el-icon>
          源库: {{ statistics.sourceRepos || 0 }}
        </div>
      </div>

      <div class="status-card">
        <div class="title">系统状态</div>
        <div class="value">
          <el-tag :type="systemStatus.type" size="large">
            {{ systemStatus.text }}
          </el-tag>
        </div>
        <div class="subtitle">
          <el-icon><Clock /></el-icon>
          运行时间: {{ systemStatus.uptime }}
        </div>
      </div>
    </div>

    <!-- 最近执行记录 -->
    <div class="page-container">
      <div class="page-header">
        <h2 class="page-title">最近执行记录</h2>
        <el-button type="primary" @click="$router.push('/executions')">
          查看全部
        </el-button>
      </div>

      <el-table
        :data="recentExecutions"
        v-loading="executionsLoading"
        element-loading-text="加载中..."
        empty-text="暂无执行记录"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="task_name" label="任务名称" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row?.status)">
              {{ getStatusText(scope.row?.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时" width="120">
          <template #default="scope">
            {{ formatDuration(scope.row?.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="执行时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row?.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <div class="table-actions">
              <el-button
                size="small"
                @click="viewExecution(scope.row?.id)"
              >
                详情
              </el-button>
              <el-button
                v-if="scope.row?.status === 'failed'"
                size="small"
                type="warning"
                @click="retryExecution(scope.row?.id)"
              >
                重试
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 系统信息 -->
    <div class="page-container">
      <div class="page-header">
        <h2 class="page-title">系统信息</h2>
        <el-button @click="refreshSystemInfo" :loading="systemInfoLoading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card title="服务状态">
            <div class="service-status">
              <div class="service-item">
                <span>API服务</span>
                <el-tag type="success">运行中</el-tag>
              </div>
              <div class="service-item">
                <span>任务队列</span>
                <el-tag :type="queueStatus.type">{{ queueStatus.text }}</el-tag>
              </div>
              <div class="service-item">
                <span>数据库</span>
                <el-tag type="success">连接正常</el-tag>
              </div>
              <div class="service-item">
                <span>Redis</span>
                <el-tag type="success">连接正常</el-tag>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card title="资源使用">
            <div class="resource-info">
              <div class="resource-item">
                <span>CPU使用率</span>
                <el-progress :percentage="systemInfo.cpuUsage || 0" />
              </div>
              <div class="resource-item">
                <span>内存使用率</span>
                <el-progress :percentage="systemInfo.memoryUsage || 0" />
              </div>
              <div class="resource-item">
                <span>磁盘使用率</span>
                <el-progress :percentage="systemInfo.diskUsage || 0" />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { executionsApi, systemApi } from '../api'

const router = useRouter()

// 数据状态
const statistics = ref({})
const recentExecutions = ref([])
const systemStatus = ref({ type: 'success', text: '正常', uptime: '0天' })
const systemInfo = ref({})
const queueStatus = ref({ type: 'success', text: '正常' })
const executionsLoading = ref(false)
const systemInfoLoading = ref(false)

// 获取统计数据
const fetchStatistics = async () => {
  try {
    console.log('正在获取统计数据...')
    const response = await systemApi.getStatistics({ days: 7 })
    console.log('统计数据响应:', response)
    statistics.value = response.data || {}
  } catch (error) {
    console.error('获取统计数据失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
  }
}

// 获取最近执行记录
const fetchRecentExecutions = async () => {
  executionsLoading.value = true
  try {
    const response = await executionsApi.getExecutions({
      page: 1,
      size: 10,
      sort: 'created_at',
      order: 'desc'
    })
    recentExecutions.value = response.data?.items || []
  } catch (error) {
    console.error('获取执行记录失败:', error)
  } finally {
    executionsLoading.value = false
  }
}

// 获取系统信息
const fetchSystemInfo = async () => {
  systemInfoLoading.value = true
  try {
    const [statusResponse, infoResponse] = await Promise.all([
      systemApi.getSystemStatus(),
      systemApi.getSystemInfo()
    ])

    systemStatus.value = statusResponse.data || {}
    systemInfo.value = infoResponse.data || {}
    queueStatus.value = {
      type: systemInfo.value.queueStatus === 'running' ? 'success' : 'warning',
      text: systemInfo.value.queueStatus === 'running' ? '正常' : '异常'
    }
  } catch (error) {
    console.error('获取系统信息失败:', error)
    systemStatus.value = { type: 'danger', text: '异常', uptime: '未知' }
  } finally {
    systemInfoLoading.value = false
  }
}

// 刷新系统信息
const refreshSystemInfo = () => {
  fetchStatistics()
  fetchSystemInfo()
}

// 查看执行详情
const viewExecution = (id) => {
  router.push(`/executions/${id}`)
}

// 重试执行
const retryExecution = async (id) => {
  try {
    await executionsApi.retryExecution(id)
    ElMessage.success('重试任务已提交')
    fetchRecentExecutions()
  } catch (error) {
    console.error('重试失败:', error)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    success: 'success',
    running: 'warning',
    failed: 'danger',
    pending: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    success: '成功',
    running: '运行中',
    failed: '失败',
    pending: '等待中'
  }
  return textMap[status] || status
}

// 格式化时长
const formatDuration = (seconds) => {
  if (!seconds) return '-'
  if (seconds < 60) return `${seconds}秒`
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}分${remainingSeconds}秒`
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  console.log('Dashboard.vue 已挂载')
  fetchStatistics()
  fetchRecentExecutions()
  fetchSystemInfo()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.service-status,
.resource-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.service-item,
.resource-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.resource-item {
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.resource-item span {
  font-weight: 500;
}
</style>